package com.yl.common.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.yl.common.utils.LogUtil;
import com.yl.common.utils.ToastUtil;

import java.lang.reflect.Field;

/**
 * Created by chenjinxu on 2019/5/26.
 * 说明:
 */
public abstract class BaseFragment extends Fragment {
    public boolean saveStatusLog = true;
    boolean isFirst = true;
    public String TAG = "TAG";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mContentView = inflater.inflate(getViewId(), container, false);
        if(saveStatusLog){
            LogUtil.getInstance().log(TAG, "--onCreateView " + this);
        }
        return mContentView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isFirst = true;
        if(saveStatusLog){
            LogUtil.getInstance().log(TAG, "--onDestroyView " + this);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(saveStatusLog) {
            LogUtil.getInstance().log(TAG, "--onHiddenChanged:" + hidden + " " + this);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter && isFirst) {
            isFirst = false;
            if (nextAnim > 0) {
                Animation anim = AnimationUtils.loadAnimation(getContext(), nextAnim);
                anim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        afterViewShow();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                return anim;
            } else {
                afterViewShow();
                return null;
            }
        } else {
            return super.onCreateAnimation(transit, false, nextAnim);
        }
    }

    public void showToast(String msg) {
        if (msg == null || getContext() == null) {
            return;
        }
        ToastUtil.getInstance().showText(msg);
    }

    public void showLoading(String title) {
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            BaseActivity baseActivity = (BaseActivity) getActivity();
            baseActivity.showLoading(title);
        }
    }

    public void hideLoading() {
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            BaseActivity baseActivity = (BaseActivity) getActivity();
            baseActivity.hideLoading();
        }
    }

    public void finish() {
        if (getFragmentManager() != null) {
            getFragmentManager().popBackStack();
        }
    }

    public void finish(String backStack) {
        if (getFragmentManager() != null) {
            try {
                getFragmentManager().popBackStack(backStack, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void attachFragment(int containerId, Fragment fragment) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(containerId, fragment);
        transaction.commit();
    }

    /**
     * 启动一个界面
     *
     * @param containerId 显示fragment的id
     * @param fragment    显示的fragment
     * @param backStack   当前fragment返回的标签
     */
    public void startFragment(int containerId, Fragment fragment, String backStack) {
        if (getFragmentManager() == null) {
            return;
        }
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out);
        transaction.add(containerId, fragment);
        transaction.hide(this);

        if (!TextUtils.isEmpty(backStack)) {
            transaction.addToBackStack(backStack);
        }
        transaction.commit();

    }

    public void startFragment(Fragment fragment, String backStack) {
        if (getFragmentManager() == null) {
            return;
        }
        int containerId = getContainerId();
        if (containerId > 0) {
            startFragment(containerId, fragment, backStack);
        }
    }

    public int getContainerId() {
        int containerId = 0;
        try {
            Class cl = Class.forName("android.support.v4.app.Fragment");
            Field field = cl.getDeclaredField("mContainerId");
            field.setAccessible(true);
            containerId = field.getInt(this);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return containerId;
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T findViewById(int id) {
        T result = (T) getView().findViewById(id);
        if (result == null) {
            throw new IllegalArgumentException("view 0x" + Integer.toHexString(id) + "doesn't exist");
        }

        return result;
    }

    public boolean isHidden(Fragment fragment) {
        if (fragment.isHidden()) {
            return true;
        }
        if (fragment.getParentFragment() != null) {
            return isHidden(fragment.getParentFragment());
        }
        return false;
    }


    public abstract int getViewId();

    /**
     * 加载完启动动画后调用次函数，将耗时操作放在这个函数里，避免出现卡顿
     */
    public abstract void afterViewShow();

    public boolean interceptBackPress() {
        return false;
    }
}
